﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Xfm
{
    /// <summary>
    /// 简单权限没什么好扩展的，已经很简单了。
    /// </summary>
    public static class XfAuthExtention
    {
        /// <summary>
        /// Xf扩展登录
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="userId">用户Id</param>
        /// <param name="userName">用户名</param>
        /// <param name="role">角色，用于[Authorize(Roles = "角色1,角色2")]</param>
        /// <param name="otherClaims">自定义的Claims</param>
        /// <returns></returns>
        public static async Task XfSignInAsync(this HttpContext httpContext, int userId, string userName, string role, IEnumerable<Claim> otherClaims = null)
        {
            if (string.IsNullOrEmpty(userName))
                throw new ArgumentNullException("用户名不能为空");
            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.NameIdentifier, userId.ToString(), ClaimValueTypes.Integer, null));
            claims.Add(new Claim(ClaimTypes.Name, userName, ClaimValueTypes.String, null));
            if (!string.IsNullOrEmpty(role))
                claims.Add(new Claim(ClaimTypes.Role, role, ClaimValueTypes.String, null));
            if (otherClaims != null)
                claims.AddRange(otherClaims);
            await httpContext.XfSignInAsync(claims);
        }
        /// <summary>
        /// Xf扩展登录，自定义的Claim集合
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="claims">Claim集合</param>
        /// <returns></returns>
        public static async Task XfSignInAsync(this HttpContext httpContext, IEnumerable<Claim> claims)
        {
            var claimsPrincipal = new ClaimsPrincipal();
            var claimsIdentity = new ClaimsIdentity(claims, "Password");
            claimsPrincipal.AddIdentity(claimsIdentity);
            await httpContext.SignInAsync(claimsPrincipal);
        }
        public static async Task XfSignOutAsync(this HttpContext httpContext)
        {
            await httpContext.SignOutAsync();
        }
    }
}
